import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import Page from './page'
import { getCookie } from '../utils'


const Router = () => {


    const BeforeEach = (props) => {
        // 获取路由信息
        const location = useLocation();

        if (!getCookie() && location.pathname !== '/login' && location.pathname !== '/sign') {
            return <Navigate to='/login' />
        }

        return props.children

    }

    const renderRouter = (routes) => {
        return routes.map((item, idx) => {
            return item.path ? <Route key={idx} path={item.path} element={<BeforeEach> {item.element} </BeforeEach>}>
                {
                    item.children && renderRouter(item.children)
                }
            </Route> : <Route key={idx} path={item.from} element={<Navigate to={item.to} />}></Route>
        })
    }

    return <BrowserRouter>
        <Routes>
            {
                renderRouter(Page)
            }
        </Routes>
    </BrowserRouter>
}

export default Router

